package com.wenx.kafkacamel;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.component.kafka.KafkaConstants;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * camel send message to kafka
 */
public class MessagePublisherClient2 extends RouteBuilder {
    private static final Logger LOG = LoggerFactory.getLogger(MessagePublisherClient2.class);

    private MessagePublisherClient2() { }

    public void configure() throws Exception {

        PropertiesComponent pc = getContext().getComponent("properties", PropertiesComponent.class);
        pc.setLocation("classpath:application-kafka.properties");

        from("direct:start").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody("Test Message from Camel Kafka Component Final",String.class);
                exchange.getIn().setHeader(KafkaConstants.PARTITION_KEY, 0);
                exchange.getIn().setHeader(KafkaConstants.KEY, "1");
            }
        }).to("kafka:{{kafka.host}}:{{kafka.port}}?topic=test1");

    }

    public static void main(String[] args) throws Exception {
        String testKafkaMessage = "Test Message from  MessagePublisherClient " + Calendar.getInstance().getTime();
        CamelContext camelContext = new DefaultCamelContext();
        camelContext.addRoutes(new MessagePublisherClient2());
        KafkaComponent kafka = new KafkaComponent();
        kafka.setBrokers("10.10.5.212:9092");
        camelContext.addComponent("kafka", kafka);
        ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
        camelContext.start();
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put(KafkaConstants.PARTITION_KEY, 0);
        headers.put(KafkaConstants.KEY, "1");
        producerTemplate.sendBodyAndHeaders("direct:start", testKafkaMessage, headers);
        // let it run for 5 minutes before shutting down
        Thread.sleep(5 * 60 * 1000);
        camelContext.stop();
    }
}
